package thread_pool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

class Worker1 extends Thread{
    private final BlockingQueue<Runnable> queue;

    public Worker1(BlockingQueue<Runnable> queue){
        this.queue = queue;
    }
    @Override
    public void run() {
        while (!Thread.interrupted()) {
            try {
                Runnable task = queue.take();
                task.run();
            } catch (InterruptedException exc){
                break;
            }
        }
    }
}

// 一开始就创建好所有线程
public class ThreadPool1 {
    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(10);
    private Thread[] workers;
    public ThreadPool1(int corePoolSize){
        workers = new Thread[corePoolSize];
        for (int i = 0; i < corePoolSize; i++){
            workers[i] = new Worker1(queue);
            workers[i].start();
        }
    }

    public void execute(Runnable task) throws InterruptedException {
        queue.put(task);
    }

    public void shutdown() throws InterruptedException {
        // 要求关闭所有线程

        for (int i = 0; i < workers.length; i++){
            Thread thread = workers[i];
            thread.interrupt();
        }

        for (int i = 0; i < workers.length; i++){
            Thread thread = workers[i];
            thread.join();
        }


    }
}
